/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    struct compare{
        bool operator()(ListNode* a, ListNode* b){
            return a->val >= b->val;
        }
    };

    ListNode* mergeKLists(vector<ListNode*>& lists) {

        priority_queue<ListNode*, vector<ListNode*>, compare()> q;
        for(auto node: lists){
            if(node) q.push(node);
        }

        ListNode head, *tail=&head;
        while(q.size()){

            ListNode* temp = q.top();
            q.pop();

            if(temp->next) q.push(temp->next);
            tail->next = temp;
            tail = tail->next;
        }

        return head->next;
    }
};